import {
    getCartList,
    changeCount,
    delSelect
} from "@/api/cart"

import { Toast } from "vant"

export default {
    namespaced: true,
    state() {
        return {
            cartList: []
        }
    },
    mutations: {
        setCartList(state, newList) {
            state.cartList = newList
        },
        changeCount(state, {
            goodsId,
            goodsNum
        }) {
            const goods = state.cartList.find(item => item.goods_id === goodsId)
            goods.goods_num = goodsNum
        },
        toggleCheck(state, goodsId) {
            const goods = state.cartList.find(item => item.goods_id === goodsId)
            goods.isChecked = !goods.isChecked
        },
        toggleAllCheck(state, flag) {
            state.cartList.forEach(item => {
                item.isChecked = flag
            })
        },
    },
    actions: {
        async getCartAction(context) {
            const {
                data
            } = await getCartList()
            data.list.forEach(item => {
                item.isChecked = true
            })
            context.commit('setCartList', data.list)
        },
        async changeCountAction(context, obj) {
            const {
                goodsNum,
                goodsId,
                goodsSkuId
            } = obj
            // 先本地修改
            context.commit('changeCount', {
                goodsId,
                goodsNum
            })
            // 再同步到后台
            await changeCount(goodsId, goodsNum, goodsSkuId)
        },
        async delSelect (context) {
            const selCartList = context.getters.selCartList
            const cartIds = selCartList.map(item => item.id)
            await delSelect(cartIds)
            Toast('删除成功')
      
            // 重新拉取最新的购物车数据 (重新渲染)
            context.dispatch('getCartAction')
        }
    },
    getters: {
        cartTotal(state) {
            return state.cartList.reduce((sum, item, index) => sum + item.goods_num, 0)
        },
        selCartList(state) {
            return state.cartList.filter(item => item.isChecked)
        },
        selCount(state, getters) {
            return getters.selCartList.reduce((sum, item, index) => sum + item.goods_num, 0)
        },
        selPrice(state, getters) {
            return getters.selCartList.reduce((sum, item, index) => {
                return sum + item.goods_num * item.goods.goods_price_min
            }, 0).toFixed(2)
        },
        isAllChecked(state) {
            return state.cartList.every(item => item.isChecked)
        }
    }
}